<template>
  <div class="main">
    <div class="font20">模型</div>
    <div class="font10 top10">上传模型</div>
    <div class="left20 top10 flex width80">
      <el-form ref="form" :model="form" label-width="150px" id="from">
        <el-form-item label="模型名称">
          <el-input
            v-model="form.modelName"
            size="medium"
            clearable
            placeholder="请输入模型名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="模型版本">
          <el-input
            v-model="form.modelTag"
            size="medium"
            clearable
            placeholder="请输入模型版本"
          ></el-input>
        </el-form-item>
        <el-form-item label="模型描述信息">
          <el-input
            v-model="form.modelDescription"
            size="medium"
            clearable
            placeholder="请输入模型描述信息"
          ></el-input>
        </el-form-item>
        <el-form-item label="模型文件类型">
          <el-input
            v-model="form.modelType"
            size="medium"
            clearable
            placeholder="请输入模型类型"
          ></el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" plain @click="creatdatas()"
              >创建模型</el-button
            >
         </el-form-item>
           <el-form-item label="选择上传的文件">
               <!--点击上传文件-->
              <div id="upload-container">
                <span>点击选择文件，项目中需要只允许单个文件上传，所以最多选择一个</span>
              </div>
              <!--这个picker是给webuploader使用的，不需要显示给用户，所以display: none;-->
              <el-button id="picker" style="display: none;">picker</el-button>
              <!--文件列表-->
              <ul id="upload-list">

              </ul>
              <!--上传按钮-->
              <el-button id="upload"  type='success' plain>点击上传</el-button>
      </el-form-item>
      </el-form>
    </div> 
  </div>
</template>
<script>
import { baseUrls } from "@/main.js";
import $ from 'jquery'
import WebUploader from 'webuploader'

export default {
  data() {
    return {
      token: "",
       modelId:'',
      form: {
        modelDescription: "",
        modelName: "",
        modelType:0,
        modelTag:""
      },
     
    };
  },

  methods: {
  
    async creatdatas() {
      let formData = new FormData();
      formData.append("modelDescription", this.form.modelDescription);
      formData.append("modelName", this.form.modelName);
      formData.append("modelType", this.form.modelType );
      formData.append("modelTag",this.form.modelTag)
      console.log(formData);

      this.$http
        .post(`${baseUrls.base2}/model`, {
          modelDescription: formData.get("modelDescription"),
          modelName: formData.get("modelName"),
          modelType: parseInt(formData.get("modelType")) ,
          modelTag:formData.get("modelTag"),
          headers: {
            // Authorization: this.token,
            "Content-Type": "application/x-www-form-urlencoded",
          },
        })
        .then((res) => {
          console.log(res.data);
          if (res.data.msg) {
            this.$message.error(res.data.msg);
          } else {
            this.$message.success("新建模型成功。");
            this.modelId=res.data.data.modelId;
            this.modelfileup();
          }
        });
    },
  modelfileup() {
        let that = this;
    $('#upload-container').click(function(event) {
		//清空文件队列，下面两行保证了每一次选择文件都会清空之前的文件，从而达到只能选择一个文件的目的
		uploader.reset();
		$('#upload-list').html("");
        $("#picker").find('input').click();
    });
	/**
	 * 上传按钮，点击后触发WebUploader的上传
	 */
	$('#upload').click(function(event) {
	    uploader.upload()
	});
    let uploader = WebUploader.create({
        swf: 'Uploader.swf',// swf文件路径
		///asset/upload/ 后面跟的是asset的id，详见swagger
        server: baseUrls.base2 + '/model/upload/'+that.modelId,// 文件接收服务端。
        pick: {
			id: '#picker',// 指定选择文件的按钮容器，根据当前运行环境在该标签内部创建一个新元素，可能是input元素，也可能是flash. 这里是div的id
			multiple: false, // 选择多个
		},
		fileNumLimit: 1, //允许文件数量（项目只支持单个文件）
        chunked: true,// 开启分片上传。
        chunkSize: 10 * 1024 * 1024, //分片大小，默认为5mb，单位byte
        threads: 5, // 上传并发数, 默认3。允许同时最大上传进程数。
        method: 'POST', // 文件上传方式，POST或者GET。	
    });

	//每次添加文件后会触发此事件
	uploader.on('fileQueued', function(file) {
	    var html = '<li><span>文件名：'+file.name+'</li>';
	    $('#upload-list').html(html);
	});
	
	//设置token，必要！！！
	uploader.on('uploadBeforeSend', function(object, data, headers) {
		headers["Authorization"] = that.token;
	});
	
	//成功
    uploader.on('uploadSuccess', function(file, response) {
        console.log(file.name+"传输成功");
        console.log(response)
         if(response.status!=200){
          that.$message.error(response.msg)
        }else{
          that.$message.success('上传成功')
        }
    });

	//失败
    uploader.on('uploadError', function(file) {
        console.log(file.name+'传输失败')
    });
      
  }
  },
  created() {
    this.token = window.sessionStorage.getItem("token");
  },
  mounted() {
    
  }

};

</script>
<style scoped>
.el-input {
  width: 40vw;
}
.file-css {
  border: none;
}
</style>
